package com.kun.reflection.demo02_memoryAnalysis;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

//反射效率计算
public class Test06_timeCal {

    //1. 普通方式调用
    public void test01() throws Exception {
        long start = System.currentTimeMillis();
        Person person = new Person();

        for (int i = 0; i < 1_000_000; i++) {
            person.getName();
        }
        long end = System.currentTimeMillis();
        System.out.println("普通方式调用耗时：" + (end - start) + "ms");
    }

    //2. 反射方式调用
    public void test02() throws Exception {
        long start = System.currentTimeMillis();
        Class personClass = Class.forName("com.kun.reflection.demo02_memoryAnalysis.Person");
        Person person = (Person) personClass.newInstance();
        Method getName = personClass.getMethod("getName");
        for (int i = 0; i < 1_000_000; i++) {
            getName.invoke(person);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射方式调用耗时：" + (end - start) + "ms");
    }

    //3. 反射方式调用--关闭安全检查
    public void test03() throws Exception {
        long start = System.currentTimeMillis();
        Class personClass = Class.forName("com.kun.reflection.demo02_memoryAnalysis.Person");
        Person person = (Person) personClass.newInstance();
        Field getName = personClass.getDeclaredField("name");
        getName.setAccessible(true);
        for (int i = 0; i < 1_000_000; i++) {
            getName.get(person);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射方式调用耗时（关闭安全检查）：" + (end - start) + "ms");
    }

    @Test
    public void test() throws Exception {
        test01();
        test02();
        test03();
    }


}
